package top.heue.epro;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import java.net.FileNameMap;
import java.net.URLConnection;

import top.heue.epro.bean.ConfigBean;
import top.heue.epro.service.WindowService;
import top.heue.epro.util.ConfigUtil;
import top.heue.epro.util.NormalUtil;
import top.heue.epro.util.PermissionUtil;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        //LOG.initLogger(context);//日志初始化
        //LOG.i("应用启动");
        PermissionUtil.isFirstRun(context);
        init();
    }

    //初始化
    private Activity context;

    private SeekBar seek_brightness;
    private SeekBar seek_alpha;
    private EditText edt_src;

    private ConfigBean config;
    @TargetApi(Build.VERSION_CODES.N)
    private void init() {
        //启动状态栏Service
        //Intent intent = new Intent(Service.ACTION_REQUEST_LISTENING);
        //intent.putExtra(Intent.EXTRA_COMPONENT_NAME, component);
        //intent.setPackage(sysuiComponent.getPackageName());
        //context.sendBroadcast(intent, Manifest.permission.BIND_QUICK_SETTINGS_TILE);
        //日志头获取
        //String c = "机型：" + android.os.Build.MODEL +
            //"\n版本：" + android.os.Build.VERSION.RELEASE +
            //"\n语言：" + java.util.Locale.getDefault().getLanguage();
        //LOG.i("配置信息", c);
        //绑定控件
        seek_brightness = findViewById(R.id.seek_brightness);
        seek_alpha = findViewById(R.id.seek_alpha);
        //View view_preview = findViewById(R.id.view_preview);
        Button btn_start = findViewById(R.id.btn_start);
        edt_src = findViewById(R.id.edt_src);

        state = findViewById(R.id.txt_state);
        version = findViewById(R.id.txt_version);
        //绑定变量
        OnSeekBarChangeListener onSeekBarChangeListener = new OnSeekBarChangeListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public void onProgressChanged(SeekBar p1, int p2, boolean p3) {
                //拖动条位置改变
                switch (p1.getId()) {
                    case R.id.seek_brightness:
                        //亮度

                        break;
                    case R.id.seek_alpha:
                        //透明度

                        break;
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar p1) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar p1) {
            }
        };
        seek_brightness.setOnSeekBarChangeListener(onSeekBarChangeListener);
        seek_alpha.setOnSeekBarChangeListener(onSeekBarChangeListener);
        @SuppressLint("NonConstantResourceId") OnClickListener onClickListener = p1 -> {
            switch (p1.getId()) {
                case R.id.btn_start:
                    //开启悬浮窗
                    //权限检查
                    if (PermissionUtil.storagePermissionCheck(context) || !PermissionUtil.checkDrawPermission(context)) {
                        //LOG.i("没有悬浮窗或存储权限");
                        //弹出提示，引导操作
                        NormalUtil.showDialog(context, "提醒", "需要申请权限：\n\n悬浮窗->本应用依靠悬浮窗\n内部存储->设置为图片时需要");
                        new Thread() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(2000);
                                } catch (InterruptedException e) {
                                 //LOG.i("线程暂停错误", e);
                                }
                                if(PermissionUtil.storagePermissionCheck(context)) {
                                    try {
                                        Thread.sleep(600);
                                    } catch (InterruptedException e) {
                                        //LOG.i("线程暂停错误", e);
                                    }
                                }
                                PermissionUtil.gotoDrawPermit(context);
                            }
                        }.start();
                    } else {
                        //LOG.i("有权限");
                        config.setBrightness(seek_brightness.getProgress());
                        if (edt_src.getText() != null && edt_src.getText().toString().length() != 0) {
                            String src = edt_src.getText().toString();
                            if (src.startsWith("#")) {//是颜色，要七位或九位
                                //LOG.i("颜色", src);
                                if (src.length() == 7 || src.length() == 9)
                                    config.setSrc(src);
                                else {
                                    //LOG.i("不支持的格式");
                                    showToast("不支持的格式");
                                    return;
                                }
                            } else if (src.startsWith("/")) {//是图片，判断是否为图片
                                FileNameMap fileNameMap = URLConnection.getFileNameMap();
                                String type = fileNameMap.getContentTypeFor(src);
                                //LOG.i("文件类型", type);
                                if (type.startsWith("image")) {
                                    //是需要的图片
                                    config.setSrc(src);
                                } else {
                                    //LOG.i("不支持的格式");
                                    showToast("不支持的格式");
                                    return;
                                }
                            } else {//不是需要的
                                //LOG.i("不支持的格式");
                                showToast("不支持的格式");
                                return;
                            }
                        }
                        config.setAlpha(seek_alpha.getProgress());
                        ConfigUtil.writeUtil(context, config);
                        Intent intent = new Intent(context, WindowService.class);
                        startService(intent);
                        finish();
                    }
                    break;
                case R.id.txt_state:
                        PermissionUtil.simpleSetting(context);
                    break;
            }
        };
        btn_start.setOnClickListener(onClickListener);
        state.setOnClickListener(onClickListener);
        //读取配置
        new Thread() {
            @Override
            public void run() {
                config = ConfigUtil.readUtil(context);
                seek_brightness.setMax(255);
                seek_alpha.setMax(255);
                seek_brightness.setProgress(config.getBrightness());
                seek_alpha.setProgress(config.getAlpha());
                edt_src.setText(config.getSrc());
                //edt_src.setLineHeight(40);
                state();
                
            }
        }.start();
        EditText edt_tips = findViewById(R.id.edt_tips);
        NormalUtil.disableShowSoftInput(edt_tips);
    }

    private void showToast(String str) {
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
    }

    //部分字体颜色
    private TextView state;
    private TextView version;
    //private boolean isPermit;
    private void state() {
        version.append(NormalUtil.getVersion(context));
        if (PermissionUtil.checkDrawPermission(context)) {
            state.append(NormalUtil.wordColor("能用", true));
        } else {
            state.append(NormalUtil.wordColor("无权", false));
        }
    }

    //返回桌面
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //LOG.i("返回桌面");
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_MAIN);// "android.intent.action.MAIN"
            intent.addCategory(Intent.CATEGORY_HOME); //"android.intent.category.HOME"
            startActivity(intent);
            return false;
        } else {
            //LOG.i("触发按键->" + keyCode);
            return super.onKeyDown(keyCode, event);
        }
    }
}
